#!/usr/bin/env php
<?php

require_once __DIR__ . '/app/config/funcs.php';

const RUNTIME = './runtime/';

$command = $argv[1] ?? 'start';

$pid = getServerPid();
$workerNum = getWorkerNum();
$stopShell = "kill -term ".$pid;
$startShell = './app/bin/syncer >> ' ."./runtime/log/app.log &";
if ($command === 'start') {
    if ($workerNum && $pid) {
        die("服务正在运行中，使用 state 指令 可查看服务运行状态" . PHP_EOL);
    }
    echo ICON_WORK."启动服务".PHP_EOL;
    shell_exec($startShell);
    echo ICON_OKAY."启动服务 Okay".PHP_EOL;
    sleep(1);
    echo getStateStr().PHP_EOL;
} elseif ($command === 'state') {
    echo ICON_WORK."查看服务状态".PHP_EOL;
    echo getStateStr().PHP_EOL;
} elseif ($command === 'stop') {
    if(getWorkerNum()){
        echo ICON_WORK."停止服务...".PHP_EOL;
        shell_exec($stopShell);
        echo ICON_WORK."服务已关闭 Okay".PHP_EOL;
    }else{
        die("当前服务未在运行！使用 state 指令可查看服务运行状态" . PHP_EOL);
    }
} elseif ($command === 'reload') {
    echo ICON_WORK."重启服务...".PHP_EOL;
    if(getWorkerNum()){
        echo ICON_WORK."停止服务...".PHP_EOL;
        shell_exec($stopShell);
    }
    echo ICON_WORK."启动服务...".PHP_EOL;
    shell_exec($startShell);
    echo ICON_OKAY."重启服务Okay".PHP_EOL;
    sleep(1);
    echo getStateStr().PHP_EOL;
} else {
    echo "请输入正确的口令[start(启动服务)、reload(重载服务)、stop(停止服务)]" . PHP_EOL;
}
